package com.ecarx.library_base.scoket;

import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelHandler;

/**
 * @author WL on 2023/04/18
 */
final class MsgServerHandler extends SimpleChannelHandler {
    private final SocketManager.ServerOS mServerOS;

    public MsgServerHandler(SocketManager.ServerOS serverOS) {
        this.mServerOS = serverOS;
    }

    /**
     * 连接关闭
     *
     * @param ctx
     * @param e
     * @throws Exception
     */
    @Override
    public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
        super.channelClosed(ctx, e);
    }

    /**
     * 连接建立
     *
     * @param ctx
     * @param e
     * @throws Exception
     */
    @Override
    public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
        super.channelConnected(ctx, e);
        SocketManager.get().onMsgServerConnected(this.mServerOS);

    }

    /**
     * 连接断开
     *
     * @param ctx
     * @param e
     * @throws Exception
     */
    @Override
    public void channelDisconnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
        super.channelDisconnected(ctx, e);
        SocketManager.get().onMsgServerDisconn(this.mServerOS);
    }

    /**
     * 消息接收
     *
     * @param ctx
     * @param e
     * @throws Exception
     */
    @Override
    public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
        super.messageReceived(ctx, e);
        ChannelBuffer channelBuffer = (ChannelBuffer) e.getMessage();
        if (null != channelBuffer)
            SocketManager.get().packetDispatch(this.mServerOS, channelBuffer);
    }

    /**
     * 异常
     *
     * @param ctx
     * @param e
     * @throws Exception
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception {
        super.exceptionCaught(ctx, e);
        if (e.getChannel() == null || !e.getChannel().isConnected()) {
            SocketManager.get().onConnectMsgServerFail(this.mServerOS);
        }
    }
}
